import java.util.ArrayList;

public class OrderRepository {

	private static OrderRepository repository;
	private static ArrayList<AbstractOrder> orders = new ArrayList<AbstractOrder>();

	private OrderRepository() {
	}

	public static OrderRepository getOrderRepository() {
		if (repository == null) {
			repository = new OrderRepository();
		}
		return repository;
	}

	public void addOrder(AbstractOrder order) {
		orders.add(order);
	}

	public boolean deleteOrder(int orderId) {
		for (int i = 0; i < orders.size(); i++) {
			AbstractOrder order = orders.get(i);
			if (order.getOrderId() == orderId) {
				orders.remove(i);
				return true;
			}
		}
		return false;
	}

	public int getStockCount() {
		return orders.size();
	}

	public ArrayList<AbstractOrder> getOrders() {
		return orders;
	}

	public AbstractOrder getOrder(int orderId) {
		for (int i = 0; i < orders.size(); i++) {
			AbstractOrder order = orders.get(i);
			if (order.getOrderId() == orderId) {
				return orders.get(i);
			}
		}
		return null;
	}

	public ArrayList<AbstractOrder> getInitializedOrders() {
		ArrayList<AbstractOrder> initializedOrders = new ArrayList<AbstractOrder>();
		for (int i = 0; i < orders.size(); i++) {
			AbstractOrder order = orders.get(i);
			if (order.getInitializedState().equals(order.getOrderState())) {
				initializedOrders.add(order);
			}
		}
		return initializedOrders;
	}

	public AbstractOrder getInitializedOrActiveOrder(int orderId) {
		for (int i = 0; i < orders.size(); i++) {
			AbstractOrder order = orders.get(i);
			if (order.getOrderId() == orderId
					&& (order.getInitializedState().equals(
							order.getOrderState()) || order.getActiveState()
							.equals(order.getOrderState()))) {
				return orders.get(i);
			}
		}
		return null;
	}

	public ArrayList<AbstractOrder> getOrdersFromAccount(int requestAccountId) {
		ArrayList<AbstractOrder> accountOrders = new ArrayList<AbstractOrder>();
		for (int i = 0; i < orders.size(); i++) {
			AbstractOrder order = orders.get(i);
			if (order.getAccountId() == requestAccountId) {
				accountOrders.add(order);
			}
		}
		return accountOrders;
	}

	public void displayAllOrders() {
		for (int i = 0; i < orders.size(); i++) {
			AbstractOrder order = orders.get(i);
			System.out.println("Account ID: " + order.getAccountId());
			System.out.println("Order ID: " + order.getOrderId());
			System.out.println("Order Price: " + order.getOrderPrice());
			System.out.println("Order Type: " + order.getOrderType());
			System.out.println("");

		}
	}

}
